set matsize 5000

capture program drop GenPolynomial
program define GenPolynomial
gen above           = totmuj>=20
gen totmuj2         = (totmuj-20)^2
gen totmuj3         = (totmuj-20)^3
gen totmuj_above    = (totmuj-20)*above
gen totmuj2_above   = (totmuj-20)^2*above
gen totmuj3_above   = (totmuj-20)^3*above
gen totmuj_original = totmuj
replace totmuj      = totmuj-20
end



capture program drop Table_Panels 
program define Table_Panels  `1' `2'

local var_number = 1
local table_name "TABLES/`2'_range`1'"
local table_name = subinstr("`table_name'", " ", "", .)

foreach y in $Outcomes_List{
if `var_number' == 1 {
	esttab `y'_* ///
	   using `table_name', keep(above) stats(N, fmt(%9.0gc)) ///
	   cells(b(fmt(%9.3f) star) se(par fmt(%9.3f))) starlevels(* 0.10 ** 0.05 *** 0.01) label replace ///
	   style(tex) booktabs title("`: var label `y''")
}
else {
	esttab `y'_* ///
	   using `table_name', keep(above) stats(N, fmt(%9.0gc)) ///
	   cells(b(fmt(%9.3f) star) se(par fmt(%9.3f))) starlevels(* 0.10 ** 0.05 *** 0.01) label append ///
	   style(tex) booktabs nonumbers title("`: var label `y''")
}
local var_number = `var_number' + 1

}

end

***************************

use DTA/Datos_ENIA_95_07_Processed.dta, clear
GenPolynomial

global SubSample all period1 period2 period3 sectorA sectorB small large 
global Outcomes_List gexval segval arrval pubval renimp patimp conimp isubval provap acavap matpco diapar priv_dom priv_foreign
local bw 10 

********************************************************************************
* Main specifications:

foreach var in $Outcomes_List{
*estimates clear

matrix P = J(8,1,.)
local i = 0 
foreach sub_sample in $SubSample {
local i = `i'+1
qui areg `var' totmuj totmuj2 totmuj_above totmuj2_above above i.year, robust a(ciiu3), if abs(totmuj) <= `bw' & `sub_sample' == 1
estimates store `var'_`sub_sample'
qui estadd local SAMPLE `sub_sample'
matrix P[`i',1] = r(table)["pvalue","above"]

*estout * using TABLES/Sector_FE/`var'_RD_range`range'.txt, keep(above) stats( r2 rmse N , fmt(%9.3f %9.3f %9.0gc)) cells(b(fmt(%9.3f) star) se(par fmt(%9.3f)) ) starlevels (* 0.10 ** 0.05 *** 0.01 ) style(tex) replace  notype mlabels(, numbers)
}
}
Table_Panels  `bw' "TableB2" 